#include <ESP8266WiFi.h>

#define MAX_SRV_CLIENTS 1            //定义可连接的客户端数目最大值
const char* ssid = "ssid";           //账号
const char* password = "password";   //密码

WiFiServer server(8888);                    //端口号
WiFiClient serverClients[MAX_SRV_CLIENTS];  //客户端

void setup() {
	
  Serial.begin(115200); 
  WiFi.mode(WIFI_AP);           //AP模式
  WiFi.softAP(ssid, password);  //配置WIFI 
  IPAddress m_ip = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(m_ip);
  
  server.begin();          //启动UART传输和服务器
  server.setNoDelay(true); //无发送延时
}

void loop() {
	
	uint8_t i;
	//检查连接
	if (server.hasClient()){//存在连接请求
		for(i = 0; i < MAX_SRV_CLIENTS; i++){
			//查找空的和已经断开连接的
			if (!serverClients[i] || !serverClients[i].connected()){
				//如果是空的
				if(!serverClients[i]){
					//停止连接
					serverClients[i].stop();
				} 
			//连接新的
			serverClients[i] = server.available();
			//提示连接成功
			Serial.print("CONNECTED"); 
			continue;
			} 
		}
	}
	//来自客户端的数据
	for(i = 0; i < MAX_SRV_CLIENTS; i++){
		if (serverClients[i] && serverClients[i].connected()){
			if(serverClients[i].available()){
				//从客户端获取数据
				while(serverClients[i].available()){
					//将数据转发到URAT端口
					Serial.write(serverClients[i].read());
				}       
			}
		}
	}
	//检查UART端口数据
	if(Serial.available()){
		size_t len = Serial.available();
		uint8_t sbuf[len];
		Serial.readBytes(sbuf, len);
		for(i = 0; i < MAX_SRV_CLIENTS; i++){
			if (serverClients[i] && serverClients[i].connected()){
				//将UART端口数据转发到已连接的客户端
				serverClients[i].write(sbuf, len);
				delay(1);
			}
		}
	}
}
